package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.type.CollectionLikeType;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo getCaptcha() {
        //验证码样式
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 6);//获取生成验证码的对象
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);//设置验证码类型，默认为数字+字母组合的验证码
        //验证码的文本信息
        String code = specCaptcha.text().toLowerCase();//将获取到的随机验证码转换为字符串的小写形式
        //图片
        String image = specCaptcha.toBase64();//将验证码图片转换为base64编码的字符串
        //key  这个key后续用户登录的时候会一并携带过来，后端需要再次验证
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();//生成一个唯一的key
        //存到redis并设置过期时间
        //保存的时候，key是唯一的，value是验证码的文本信息，形成键值对存进去
        stringRedisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);//

        CaptchaVo captchaVo = new CaptchaVo(image, key);//封装验证码图片和key
        return captchaVo;
    }

    @Override
    public String login(LoginVo loginVo) {
        //账号
        String username = loginVo.getUsername();
        //密码
        String password = loginVo.getPassword();
        //验证码
        String captchaCode = loginVo.getCaptchaCode();
        //验证码在redis中的key
        String captchaKey = loginVo.getCaptchaKey();

        //1 校验验证码是否未输入
        if (!StringUtils.hasText(captchaCode)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //获取存在redis中的code
        String redisCode = stringRedisTemplate.opsForValue().get(captchaKey);
        //如果验证码已过期，啊么自动删除该验证码
        if (captchaKey == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //对比客户输入的验证码和我们的验证码是否一致
        if (!captchaCode.equals(redisCode)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        //3 校验用户是否存在
        //3-1 从数据库中获取同名的用户对象
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername, username);
        SystemUser systemUser = systemUserMapper.selectOne(queryWrapper);
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        // 4校验用户是否被禁用
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //比较密码是否一致
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(password))){
            System.out.println("密码是："+systemUser.getPassword()+"--"+DigestUtils.md5Hex(password));
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //5 创建token并返回去
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());

        return token;
    }

    @Override
    public SystemUserInfoVo getSystemUserInfoById(Long userId) {
        SystemUser systemUser = systemUserMapper.selectById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
